//
//  HYFStatusViewModel.swift
//  MyWeibo
//
//  Created by 黄勇锋 on 16/7/25.
//  Copyright © 2016年 黄勇锋. All rights reserved.
import UIKit

class HYFStatusViewModel: NSObject {
    
    //定义一个属性
    var status:HYFStatus?
    
    // 微博认证用户图片
    var avatarImage: UIImage?
    //处理会员等级图片
    var memberImage: UIImage?
    
    //微博来源
    var sourceAttr:NSMutableAttributedString?
    
    //转发,评论,赞
    var repostsCountStr:String?
    var commentCountStr:String?
    var attitudesCountStr:String?
    
    //微博时间(只读属性,计算型)
    var sinaTimeStr:String?{
        
        return NSDate.sinaDate(status?.created_at ?? "")?.sinaDescriptionStr
    }
    
    //原创微博富文本
    var originalContentAttr:NSMutableAttributedString?
    //转发微博富文本
    var retweetContentAttr:NSMutableAttributedString?
    
    //重载构造函数
    init(status:HYFStatus) {
        
        super.init()
        
        self.status = status
        
        self.avatarImage = getAvatarImage(status.user?.verified)
        self.memberImage = getMemberImage(status.user?.mbrank)
        self.sourceAttr = getSourceStr(status.source)
        
        self.repostsCountStr = getSinaCount(status.reposts_count, title: "转发")
        self.commentCountStr = getSinaCount(status.comments_count, title: "评论")
        self.attitudesCountStr = getSinaCount(status.attitudes_count, title: "赞")
        
        self.originalContentAttr = dealContentText(status.text)
        self.retweetContentAttr = dealContentText(status.retweeted_status?.text)
        
    }
    
    // 处理表情字符串
    /*
     上海三期[笑cry]x[笑cry]x[笑cry]x[笑cry]
     上海三期表表表表
     01 [笑cry]     chs
     02 emoticon.chs   如果相同的 emoticon
     03 通过emoticon.path  得到image  文本附件  富文本
     */
    
    /*
     - 正向遍历 导致富文本越界 崩溃
     [哈哈]和[哈哈]  range  （0,4）  range (5,4)
     *和[哈哈]
     *和*
     - 解决方法
     - 创建一个模型
     - string
     - range
     - 创建一个可变的临时数组 保存 这个模型
     - 倒着遍历可变的临时数组
     - 通过当前模型到表情一位数组中找对应的emoticon
     - 得到富文本
     - 替换富文本
     */
    
    
    func dealContentText(text:String?)->NSMutableAttributedString?{
        
        //判断是否有值
        guard let t = text else{
            return nil
        }
        
        //得到一个富文本
        let allTextAttr = NSMutableAttributedString(string: t)
        
        // [笑cry]
        // 正则格式
        let regex = "\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]"
        
        //MARK: 创建一个临时可变数组
        var tempArray:[HYFMatchResult] = [HYFMatchResult]()
        
        (t as NSString).enumerateStringsMatchedByRegex(regex) { (count, string, range, _) -> Void in
            //           // printLog(string.memory)
            
            printLog(string.memory)
            //创建一个 模型
            let matchResult = HYFMatchResult(string: string.memory as? String, range:range.memory)
            tempArray.append(matchResult)
            
        }
        
        //倒序遍历数组
        for match in tempArray.reverse(){
            
            guard let emoticon = HYFEmoticonTools.sharedTools.searchEmoticons(match.string) else{
                
                continue
            }
            
            let lineHeight = UIFont.systemFontOfSize(15).lineHeight
            let attr = NSAttributedString(emoticon: emoticon, y: -4, lineHeight: lineHeight)
            
            allTextAttr.replaceCharactersInRange(match.range, withAttributedString: attr)
            
            
            
        }
        
        return allTextAttr
    }
    
}


extension HYFStatusViewModel{
    
    // 处理微博认证用户图片/// 认证类型 -1：没有认证，1，认证用户，2,3,5: 企业认证，220: 达人
    func getAvatarImage(verified: Int?) -> UIImage?{
        // 判读他是否为nil
        guard let ver = verified else{
            return nil
        }
        
        switch ver {
        case 1:
            return UIImage(named: "avatar_vip")
        case 2,3,5:
            return UIImage(named: "avatar_enterprise_vip")
        case 220:
            return UIImage(named: "avatar_grassroot")
        default:
            return UIImage(named: "avatar_vgirl")
        }
        
    }
    
    // 处理会员等级图片/// 会员等级 1-6
    func getMemberImage(mbrank: Int?) -> UIImage?{
        // 判断他是否为nil
        guard let mbr = mbrank else {
            return nil
        }
        if mbr > 0 && mbr < 7 {
            return UIImage(named: "common_icon_membership_level\(mbr)")
        }
        return UIImage(named: "common_icon_membership")
    } 
}

extension HYFStatusViewModel {
    
    func getSourceStr(source:String?) -> NSMutableAttributedString{
        
        //判断是否为 nil ,而且是否包含 ">
        guard let s = source where s.containsString("\">") else{
            let str = "上海3期微博"
            //这里不能写成 getSourceStr(自己调用自己),否则会出现循环调用(导致系统崩溃)
            return getSourceAttr(str)
        }
        
        //  <a href="http://app.weibo.com/t/feed/1tqBja" rel="nofollow">360安全浏览器</a>
        //  截取  "360安全浏览器"
        //起始位置
        let startRange = s.rangeOfString("\">")!
        let endRange = s.rangeOfString("</")!
        
        //字符串截取
        let result = s.substringWithRange(startRange.endIndex..<endRange.startIndex)
        
        return getSourceAttr(result)
    }
    
    func getSourceAttr(result:String)->NSMutableAttributedString{
        
        //最终显示格式
        let name = "来自" + result
        //得到range
        let range = (name as NSString).rangeOfString("来自")
        //创建一个可变富文本
        let attr = NSMutableAttributedString(string: name)
        //设置属性
        attr.addAttributes([NSForegroundColorAttributeName:UIColor.grayColor()], range: range)
        
        return attr
    }
    
}

extension HYFStatusViewModel {
    
    // 处理逻辑问题
    func getSinaCount(count:Int,title:String) -> String{
        
        if count <= 0 {
            
            return title
        }else {
            
            if count < 10000{
                
                return "\(count)"
            }else{
                
                let sinaCount = CGFloat(count/1000)/10
                //字符串拼接
                var sinaCountStr = "\(sinaCount)万"
                //如果 是 2.0万
                if sinaCountStr.containsString(".0"){
                    
                 //字符串替换
                    sinaCountStr = sinaCountStr.stringByReplacingOccurrencesOfString(".0", withString: "")
                    
                }
                
                return sinaCountStr
            }
        }
    }
}










